package com.musicapp;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;

import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.provider.Settings;
import android.util.AttributeSet;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

public class FirstFragment extends Fragment {
//    FinishObservable finishObservable = new FinishObservable();
    private boolean finish = false;
    public static List<ItemModel> itemList1 = new ArrayList<>();
    public static List<ItemModel> itemList2 = new ArrayList<>();
    public static List<ItemModel> itemList3 = new ArrayList<>();
    public static List<ItemModel> itemList4 = new ArrayList<>();
    private static final int REQUEST_CODE_OVERLAY_PERMISSION = 123;
    private Floating floatingView;
    public static List<SongModel> songList = new ArrayList<>();
    private RecyclerView recyclerView;
    private SwipeRefreshLayout swipeRefreshLayout;
    private final OkHttpClient okHttpClient = new OkHttpClient.Builder().build();
    private Handler handler = new Handler(Looper.getMainLooper());

    public FirstFragment(){
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //        网络请求获取数据
        Request request = new Request.Builder()
                .get()
                .url("https://hotfix-service-prod.g.mi.com/music/homePage")
                .addHeader("content-type","application/json")
                .build();

        okHttpClient.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(@NonNull Call call, @NonNull IOException e) {
                Toast.makeText(getContext(),"网络请求失败",Toast.LENGTH_SHORT).show();
            }
            @Override
            public void onResponse(@NonNull Call call, @NonNull Response response) throws IOException {
                if (response.isSuccessful()){
                    String responseBody = response.body().string();
                    handler.post(()->{
                        responseData(responseBody,recyclerView);
                        finish = true;
                    });
                }else {
                    Toast.makeText(getContext(),"无法返回结果"+response.code(),Toast.LENGTH_SHORT).show();
                }
            }
        });

//        finishObservable.setFinish(finish);
//        finishObservable.addObserver(finish -> {
//            if (finish) {
//                Log.i("XXX", "3");
//            }
//        });


    }

//    @Override
//    public void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
//        super.onActivityResult(requestCode, resultCode, data);
//        if (requestCode == REQUEST_CODE_OVERLAY_PERMISSION) {
//            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M && Settings.canDrawOverlays(requireContext())) {
//                // 创建并显示悬浮窗
//                floatingView = new Floating(requireContext());
//                floatingView.show();
//            }
//        }
//    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container,
                             @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.firstpage, container, false);

//        瀑布流
        recyclerView = view.findViewById(R.id.precyclerView);
        RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(getActivity());
        recyclerView.setLayoutManager(layoutManager);

        return view;
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        //        下拉刷新
        swipeRefreshLayout = view.findViewById(R.id.swipe);
        swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                refresh();
            }
        });

        //      悬浮View
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M && !Settings.canDrawOverlays(requireContext())) {
            // 请求用户授予权限
            Intent intent = new Intent(Settings.ACTION_MANAGE_OVERLAY_PERMISSION, Uri.parse("package:" + requireContext().getPackageName()));
            startActivityForResult(intent, REQUEST_CODE_OVERLAY_PERMISSION);
        } else {
            // 创建并显示悬浮窗
            floatingView = new Floating(requireContext());
            floatingView.show();
        }


    }

    @Override
    public void onStart() {
        super.onStart();
        floatingView.reshow();
    }

    @Override
    public void onPause() {
        super.onPause();
        floatingView.hide();
    }

    //    请求数据解析
    private static void responseData(String responseBody,RecyclerView recyclerView){
        Gson gson = new Gson();
        JsonObject jsonObject = gson.fromJson(responseBody,JsonObject.class);

        int code = jsonObject.getAsJsonPrimitive("code").getAsInt();
        String msg = jsonObject.getAsJsonPrimitive("msg").getAsString();
        if(code == 200 && "success".equals(msg)){
            JsonObject data = jsonObject.getAsJsonObject("data");
            JsonArray recordsArray = data.getAsJsonArray("records");

            for (JsonElement recordElement : recordsArray) {
                JsonObject recordObject = recordElement.getAsJsonObject();

                // 提取模块信息
                int style = recordObject.getAsJsonPrimitive("style").getAsInt();
                if(style==1){
                    // 获取 musicInfoList 数组
                    JsonArray musicInfoArray = recordObject.getAsJsonArray("musicInfoList");
                    for (JsonElement musicInfoElement : musicInfoArray) {
                        JsonObject musicInfoObject = musicInfoElement.getAsJsonObject();
                        int id = musicInfoObject.getAsJsonPrimitive("id").getAsInt();
                        String coverImage = musicInfoObject.getAsJsonPrimitive("coverUrl").getAsString();
                        String musicName = musicInfoObject.getAsJsonPrimitive("musicName").getAsString();
                        String author = musicInfoObject.getAsJsonPrimitive("author").getAsString();
                        String musicUrl = musicInfoObject.getAsJsonPrimitive("musicUrl").getAsString();
                        String lyricUrl = musicInfoObject.getAsJsonPrimitive("lyricUrl").getAsString();
                        ItemModel itemModel = new ItemModel(id,coverImage,musicName,author,musicUrl,lyricUrl);
                        itemList1.add(itemModel);
                    }
                }
                if(style==2){
                    JsonArray musicInfoArray = recordObject.getAsJsonArray("musicInfoList");
                    for (JsonElement musicInfoElement : musicInfoArray) {
                        JsonObject musicInfoObject = musicInfoElement.getAsJsonObject();
                        int id = musicInfoObject.getAsJsonPrimitive("id").getAsInt();
                        String coverImage = musicInfoObject.getAsJsonPrimitive("coverUrl").getAsString();
                        String musicName = musicInfoObject.getAsJsonPrimitive("musicName").getAsString();
                        String author = musicInfoObject.getAsJsonPrimitive("author").getAsString();
                        String musicUrl = musicInfoObject.getAsJsonPrimitive("musicUrl").getAsString();
                        String lyricUrl = musicInfoObject.getAsJsonPrimitive("lyricUrl").getAsString();
                        ItemModel itemModel = new ItemModel(id,coverImage,musicName,author,musicUrl,lyricUrl);
                        itemList2.add(itemModel);
                    }
                }
                if(style==3){
                    JsonArray musicInfoArray = recordObject.getAsJsonArray("musicInfoList");
                    for (JsonElement musicInfoElement : musicInfoArray) {
                        JsonObject musicInfoObject = musicInfoElement.getAsJsonObject();
                        int id = musicInfoObject.getAsJsonPrimitive("id").getAsInt();
                        String coverImage = musicInfoObject.getAsJsonPrimitive("coverUrl").getAsString();
                        String musicName = musicInfoObject.getAsJsonPrimitive("musicName").getAsString();
                        String author = musicInfoObject.getAsJsonPrimitive("author").getAsString();
                        String musicUrl = musicInfoObject.getAsJsonPrimitive("musicUrl").getAsString();
                        String lyricUrl = musicInfoObject.getAsJsonPrimitive("lyricUrl").getAsString();
                        ItemModel itemModel = new ItemModel(id,coverImage,musicName,author,musicUrl,lyricUrl);
                        itemList3.add(itemModel);
                    }
                }
                if(style==4){
                    JsonArray musicInfoArray = recordObject.getAsJsonArray("musicInfoList");
                    for (JsonElement musicInfoElement : musicInfoArray) {
                        JsonObject musicInfoObject = musicInfoElement.getAsJsonObject();
                        int id = musicInfoObject.getAsJsonPrimitive("id").getAsInt();
                        String coverImage = musicInfoObject.getAsJsonPrimitive("coverUrl").getAsString();
                        String musicName = musicInfoObject.getAsJsonPrimitive("musicName").getAsString();
                        String author = musicInfoObject.getAsJsonPrimitive("author").getAsString();
                        String musicUrl = musicInfoObject.getAsJsonPrimitive("musicUrl").getAsString();
                        String lyricUrl = musicInfoObject.getAsJsonPrimitive("lyricUrl").getAsString();
                        ItemModel itemModel = new ItemModel(id,coverImage,musicName,author,musicUrl,lyricUrl);
                        itemList4.add(itemModel);
                    }
                }
                TotalAdapter totalAdapter = new TotalAdapter(itemList1,itemList2,itemList3,itemList4);
                recyclerView.setAdapter(totalAdapter);
            }

//            总体数据信息
//            int total = data.getAsJsonPrimitive("total").getAsInt();
//            int size = 5;
//            int current = data.getAsJsonPrimitive("current").getAsInt();
//            int pages = data.getAsJsonPrimitive("pages").getAsInt();
        }
    }

    //    下拉刷新
    public void refresh(){
        new android.os.Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                swipeRefreshLayout.setRefreshing(false);
            }
        },1000);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (floatingView != null) {
            floatingView.destroy();
        }
    }
}